package com.wxg.spring.boot.blog.v1.repository;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

import org.springframework.stereotype.Repository;

import com.wxg.spring.boot.blog.v1.domain.UserV1;

/**
 * CreateTime: 2018年10月29日 上午10:46:28
 *
 * @author wxg
 */
@Repository
public class UserRepositoryImplV1 implements UserRepositoryV1 {

    private static AtomicLong counter = new AtomicLong();
    private final ConcurrentHashMap<Long, UserV1> userMap = new ConcurrentHashMap<>();

    @Override
    public UserV1 saveOrUpdateUser(UserV1 user) {
        Long id = user.getId();
        if (id == null) {
            id = counter.incrementAndGet();
            user.setId(id);
        }
        this.userMap.put(id, user);
        return user;
    }

    @Override
    public void deleteUser(Long id) {
        userMap.remove(id);
    }

    @Override
    public UserV1 getUserById(Long id) {
        return userMap.get(id);
    }

    @Override
    public List<UserV1> listUsers() {
        return new ArrayList<UserV1>(userMap.values());
    }

}
